﻿using DataCollection.ChangeCode;
using DataCollection.Config;
using DataCollection.Manage;
using RQX.Common.Core.Db.SqlServer;
using RQX.Common.Core.Extension;
using RQX.Common.Core.Logger;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace DataCollection
{
    public class MYSQLDB
    {
        private static readonly string SimulatePlugName = "模拟采集";
        public static Action<string> ShowMsgHandler;

        public static BaseSqlHelper sqlHelper = new BaseSqlHelper();

        private static ConcurrentQueue<string> queue_sql = new ConcurrentQueue<string>();

        static MYSQLDB()
        {
            DealQueueSql();
        }

        public static void BuildDataFormart(Dictionary<string, string> datas, string guid)
        {
            var plugName = "";
            var ip = "";
            if (guid.IsNullOrEmpty())
            {
                plugName = SimulatePlugName;
                ip = "127.0.0.1";
            }
            else
            {
                var info = DeviceInfo.list.Find(k => k.GUID.Equals(guid));
                if (info == null) return;
                plugName = info.PlugName;// row["PlugIn"].ToString();
                ip = info.DeviceName;// row["TerminalIp"].ToString();
            }
            
            var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            List<EquipmentData> list = new List<EquipmentData>();
            foreach (var item in datas)
            {
                var tl = item.Key.Split("Я");
                list.Add(new EquipmentData()
                {
                    Code = (tl.Length == 2) ? tl[0] : "",
                    ITEM_CHANNEL = (tl.Length == 2) ? tl[1] : item.Key,
                    ITEM_VALUE = item.Value.ToString(),
                    COLLECT_TIME = time
                });
            }
            InsertMonitoringdata(ip, plugName, list);
        }

        private static void InsertMonitoringdata(string ip, string plugName, List<EquipmentData> datas)
        {
            List<string> sqlList = new List<string>();
            for (int i = 0; i < datas.Count; i++)
            {
                string ITEM_CHANNEL = datas[i].ITEM_CHANNEL;
                string ITEM_ID = datas[i].ITEM_CHANNEL;

                CodeInfo info;
                if (plugName.Equals(SimulatePlugName))
                {
                    info = CodeInfo.list.Find(k =>k.Code.ToString().Equals(datas[i].Code));
                }
                else
                {
                    info = CodeInfo.list.Find(k => k.SourceCode.IsNotNull() && k.SourceCode.Count > 0 && k.SourceCode.Where(m => m.PlugName.Equals(plugName) && m.CollectionName.Equals(datas[i].ITEM_CHANNEL)).Count() == 1);
                }
                if (info.IsNotNull())
                {
                    ITEM_CHANNEL = info.Name;// query.First().Field<string>("Channel").ToString();
                    ITEM_ID = info.Code.ToString();// query.First().Field<string>("ChannelId").ToString();
                    string sql = @"INSERT INTO [TH_BUSI_OBS_DATA] (
                                    [KEYID]
                                   ,[TIMESEND]
                                   ,[OBSERVEID] 
                                   ,[OBSERVENAME]
                                   ,[OBSERVEVALUE]
                                   ,[SOURCE]
                                   ,[IP]
                                    ) values
                                ('" + Guid.NewGuid().ToString() + @"',
                                '" + datas[i].COLLECT_TIME + @"',
                                --CONVERT(VARCHAR(20),GETDATE(),20),
                                '" + ITEM_ID + @"',
                                '" + ITEM_CHANNEL + @"',
                                '" + datas[i].ITEM_VALUE + @"',
                                '" + ip + @"', 
                                '" + LocalConfig.info.Name + "')";
                    queue_sql.Enqueue(sql);
                }
                //else
                //{
                //    LogUtils.WriteDebugLog($"未找到info");
                //}
            }
        }
        /// <summary>
        /// 处理队列中的sql
        /// </summary>
        private static void DealQueueSql()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    var sqlList = new List<string>();
                    while (queue_sql.TryDequeue(out var str))
                    {
                        sqlList.Add(str);
                    }
                    if (sqlList.Count > 0)
                    {
                        try
                        {
                            var successCount = sqlHelper.ExcuteSqlNoQuery(sqlList);
                            ShowMsgHandler?.Invoke($"插入数据成功：{successCount}");
                        }
                        catch (Exception ex)
                        {
                            ShowMsgHandler?.Invoke($"插入数据异常：{ex}");
                            LogUtils.WriteErrorLog($"插入数据异常：{ex}", LocalConfig.info.Name);
                        }
                    }
                    Thread.Sleep(1000);
                }
            });
        }
    }

    public class EquipmentData
    {
        public string Code { get; set; }
        public string ITEM_VALUE { get; set; }
        public string COLLECT_TIME { get; set; }
        public string ITEM_CHANNEL { get; set; }
    }
}
